<?php

namespace app\adminapi\logic\system;

use adminmatrix\admin\logic\BaseLogic;
use adminmatrix\admin\annotation\Inject;
use app\adminapi\model\Admin\{Admin  , AdminRoles , AdminRolePermission , AdminPermission};
use think\exception\HttpException;

class PermissionLogic extends BaseLogic
{
    #[Inject]
    protected AdminPermission $model;

    public function save( $request ) : bool
    {
        return $this->model->save($request->post());
//        return true;
    }

    public static function getAllAuth()
    {
        return (new AdminPermission) -> distinct(true)
            ->where([
                ['perms', '<>', '']
            ])
            ->column('perms');
    }

    public static function getAuthByAdminId($id){
        $roleIds = ( new AdminRoles) -> where('admin_id' , $id)->column('role_id');
        $menuId = (new AdminRolePermission) -> whereIn('role_id' , $roleIds) -> column("permission_id");
        return (new AdminPermission) -> distinct(true)
            ->where([
                ['perms', '<>', ''],
                ['id', 'in' ,array_unique($menuId)]
            ])
            ->column('perms');
    }

    public function update( $request ) : bool
    {
        $result = $this->model->where('id' , $request->put('id'))->findOrEmpty();
        if($result->isEmpty())
        {
            throw new HttpException(200 , '数据不存在');
        }
        return $result->save($request->put());
    }


    public function getPermis(int $adminId) : array
    {
       $admin = Admin::where('id' , $adminId)->find();
     
        if ($adminId == 1 || $admin->root  === 1)
        {
            $permission = buildTree((new AdminPermission)
                -> whereNotIn('type',[3])->hidden(['create_time' ,'update_time','delete_time'])->select()->toArray());
        }else{
            $ids = AdminRolePermission::whereIn('role_id' , $admin->role->column('role_id'))->column("permission_id");
            $permission = buildTree((new AdminPermission)
                ->whereIn('id   ',$ids)
                -> whereNotIn('type',[3])->hidden(['create_time' ,'update_time','delete_time'])->select()->toArray());
        }

         # 获取管理员权限
         $admin = Admin::where('id' , $adminId) -> find();

         $paths = App()->getRootPath() . "app/*/";
         $deny_app_list = config('app.deny_app_list');
         $deny_app_list = array_merge($deny_app_list , ['index']);
         #获取全部应用
         $apps = glob($paths);
         $apps_name = [];
         foreach ($apps as $app) {
             $app_name = basename($app);
             if (in_array($app_name, $deny_app_list)) {
                 continue;
             }
             $config_path = $app . "config.json";
             $config = [];
             if (file_exists($config_path)) {
                 $config_content = file_get_contents($config_path);
                 if (!empty($config_content)) {
                     $config = json_decode($config_content, true) ?: [];
                 }
             }
             if($config && $config['group'] == 'admin'){
                 $apps_name[] = [
                     ...$config,
                     'hidden' => false,
                     'type' => 1,
                     'children' =>$permission
                 ];
             }
         }

        return  $apps_name;
    }
}